import { getInbound,getInboundDetail ,downloadFileByUrl} from '@/services/erp/api';
import { PlusOutlined ,QuestionCircleOutlined,DownloadOutlined,InboxOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  PageContainer,
  ProDescriptions,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import {  useModel } from '@umijs/max';
import { Button, Drawer,  message, Tooltip,Upload ,Alert  } from 'antd';
import type { UploadProps } from 'antd';
import React, { useRef, useState } from 'react';
const isDev = process.env.NODE_ENV === 'development';
import FileSaver from 'file-saver';
const { Dragger } = Upload;
const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [showUpload, setShowUpload] = useState<boolean>(false);
  const [uploadSuccess, setUploadSuccess] = useState<boolean>(false);
  const [storeInfo, setStoreInfo] = useState<String>("");
  const [currentRow, setCurrentRow] = useState<API.StockListItem>();
  const ref = useRef<ProFormInstance>();
  const columns: ProColumns<API.StockListItem>[] = [
    {
      title: "序号",
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: "入库方式",
      dataIndex: 'type',
      hideInSearch:true,
    },
    {
      title: "总价格",
      dataIndex: 'totalPrice',
      valueType: 'money',
      hideInSearch:true,
    },
    {
      title: "总数量",
      dataIndex: 'totalCount',
      hideInSearch:true,
    },
    {
      title: "种类数量",
      dataIndex: 'skuCount',
      hideInSearch:true,
    },
    {
      title: "操作员",
      dataIndex: 'operator',
      hideInSearch:true,
    },
    {
      title: "提交时间",
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="detail"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true)
          }}>
          查看详情
        </a>
      ],
    },
  ];

  const columnsDetail:[] = [
    {
      title: "商品名称",
      dataIndex: 'name',
      hideInSearch:true,
      key: 'name',
    },
    {
      title: "库存变动",
      dataIndex: 'changedStock',
      hideInSearch:true,
      key: 'changedStock',
    },

    {
      title: "商品价格",
      dataIndex: 'price',
      valueType: 'money',
      key: 'price',
      hideInSearch:true,
    },
  ];

  const props: UploadProps = {
    name: 'file',
    action: initialState?.baseURL+`api/merchant/inbounds/upload/`+initialState?.currentStoreKey,
    headers: {
      Authorization: `Bearer ${initialState?.currentUser?.token}`,
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 入库单文件导入成功 `+info.file.response?.msg);
        setUploadSuccess(true)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 入库单文件导入失败 `+info.file.response?.msg);
      }
    },
  };

  const dowmloadFile = async (url:String) => {
    console.log('dowmloadFile--->',url);
    downloadFileByUrl(url).then(res => {
      console.log('dowmloadFile--dlResult->',res);
      var blob = new Blob([res], {type: "text/plain;charset=utf-8"});
      FileSaver.saveAs(blob, "入库单导入示例文件.csv");
    })
  }

  const showUploadDraw = async () =>{
    setShowUpload(true)
    setUploadSuccess(false)
    var name = localStorage.getItem("currentStoreName")
    setStoreInfo("门店编号："+initialState?.currentStoreKey + " 名称："+name)
  }

  return (
    <PageContainer>
      <ProTable<API.StockListItem, API.PageParams>
        headerTitle="入库单列表"
        rowKey="key"
        cardBordered
        search={false}
        options={false}
        columns={columns}
        formRef={ref}
        request={async (params, sorter, filter) => {
          const msg = await getInbound(initialState?.currentStoreKey,{
            page: params.current-1,
            size: params.pageSize,
            ...params
          });
          return {
            data: msg.data,
            success: true,
            total: msg.dataSize,
          };
        }}
        toolBarRender={() => [
          <Button onClick={() => showUploadDraw()} key="primary" type="primary" shape="round" icon={<PlusOutlined />} danger>
            入库单导入
          </Button>,
          <Button key="primary" type="primary" icon={<DownloadOutlined />} shape="round"
            onClick={() => dowmloadFile("https://erp.camelee.cn/stocks.csv")}>
                下载示例文件
          </Button>,
           <Tooltip title="操作教程，1分钟教你怎么导入">
           <Button shape="round" type="primary" onClick={() => { window.open('http://erp.camelee.cn/ERP20220830.pdf');}}>
            导入教程
           </Button>
         </Tooltip>,
          <Tooltip title="入库单导入数据结果：1.库存处理：在原有的基础上加上入库单的库存； 2.商品处理：新增商品不添加进商品库">
            <span> 提示 <QuestionCircleOutlined /></span>
          </Tooltip>,
        ]}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={true}
      >
        {currentRow?.type && (
          <div>
            <ProDescriptions<API.StockListItem>
              column={2}
              request={async () => ({
                data: currentRow || {},
              })}
              columns={columns}
            />
            <ProTable<API.StockListItem, API.PageParams>
              headerTitle="入库商品"
              rowKey="key"
              cardBordered
              search={false}
              options={false}
              columns={columnsDetail}
              request={async (params, sorter, filter) => {
                const msg = await getInboundDetail(currentRow._id,{
                  page: params.current-1,
                  size: params.pageSize,
                  ...params
                });
                return {
                  data: msg.data,
                  success: true,
                  total: msg.dataSize,
                };
              }}
            />
          </div>
        )}
      </Drawer>
      <Drawer
        width={600}
        title="入库单导入"
        open={showUpload}
        onClose={() => {
          setShowUpload(false);
          if(uploadSuccess){
            window.location.reload()
          }
        }}
        closable={true}
      >
        <Alert message="数据导入后不能撤回操作，请慎重操作！" type="warning" showIcon />
        <Alert
          message="当前门店信息"
          description={storeInfo}
          type="info"
          showIcon
        />
           <Dragger  {...props} height= {200}>
               <p className="ant-upload-drag-icon">
                 <InboxOutlined />
               </p>
              <p className="ant-upload-text">点击 或 拖拽文件到这里 导入 </p>
          </Dragger>,
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
